﻿
__all__ = ['getvalue', 'setvalue', 'guid', 'getobject', 'releaseobject', 'zipto', 'unzipfrom', 'polar']

from pycad.system import *

_dict = {}

def getvalue(key):
    global _dict
    return _dict.get(key)

def setvalue(key, value = None):
    global _dict
    _dict[key] = value

def guid(gid = None):
    from System import Guid
    return gid and Guid(gid) or Guid.NewGuid()

def getobject(progid):
    try:
        from System.Runtime.InteropServices import Marshal
        return Marshal.GetActiveObject(progid)
    except:
        try:
            from System import Type, Activator
            t = Type.GetTypeFromProgID(progid)
            return Activator.CreateInstance(t)
        except: pass

def releaseobject(obj):
    from System.Runtime.InteropServices import Marshal
    return Marshal.ReleaseComObject(obj)

def zipto(dirname, zipfilename):
    import os, os.path
    import zipfile
    z = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
    if os.path.isfile(dirname):
        filename = os.path.basename(dirname)
        z.write(filename, dirname)
    else:
        if dirname[-1] in ('\\', '/'):
            dirname = dirname[:-1]
        d = len(dirname)
        for filename in (
            os.path.join(root, filename)
            for root, _, files in os.walk(dirname) 
            for filename in files):
            z.write(filename[d:], filename)
    z.close()

def unzipfrom(zipfilename, dirname):
    import os, os.path
    import zipfile
    if not os.path.exists(dirname): os.mkdir(dirname)
    zfobj = zipfile.ZipFile(zipfilename)
    for name in zfobj.namelist():
        name = name.replace('\\','/')
        if name.endswith('/'):
            os.mkdir(os.path.join(dirname, name))
        else:            
            ext_filename = os.path.join(dirname, name)
            ext_dir= os.path.dirname(ext_filename)
            if not os.path.exists(ext_dir): os.mkdir(ext_dir)
            outfile = open(ext_filename, 'wb')
            outfile.write(zfobj.read(name))
            outfile.close()

def polar(pt, angle, dist):
    return pt + acge.Vector3d.XAxis.RotateBy(angle, acge.Vector3d.ZAxis) * dist


